package dmt16.TelemetrySuit.UI.Tiles
{
	import dmt16.TelemetrySuit.Controller.SensorTypes.GPSModule;
	import dmt16.TelemetrySuit.Controller.SensorTypes.ISensorType;
	import dmt16.TelemetrySuit.Controller.SensorTypes.SensorEvent;
	import dmt16.TelemetrySuit.UI.Assets.Fonts;
	import dmt16.TelemetrySuit.UI.Assets.SpeedometerGFX;
	import dmt16.TelemetrySuit.UI.Colours;
	import dmt16.TelemetrySuit.Utils.NMEASentence;
	
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.events.Event;
	import flash.geom.Matrix;
	import flash.text.TextField;
	import flash.text.TextFormat;
	import flash.text.TextFormatAlign;
	
	public class SpeedTile extends TileBase
	{
		public function SpeedTile(sensor:ISensorType=null)
		{
			_tileGFX=new SpeedometerGFX();
			tileContent=_tileGFX;
			
			_gpsSensor=sensor as GPSModule;
			if(_gpsSensor)
				_gpsSensor.addEventListener(SensorEvent.SENSOR_DATA_EVENT,_onSensorData);
			
			_tileGFX.width=WIDTH;
			_tileGFX.height=HEIGHT;
			_pointer=DisplayObjectContainer(_tileGFX.getChildAt(0)).getChildAt(1);
			_gtxt=new TextField();
			_gtxt.embedFonts=true;
			_gtxt.selectable=false;
			_gtxt.defaultTextFormat=_textFormat;
			_gtxt.x=0;
			_gtxt.width=WIDTH-20*WIDTH/300;
			_gtxt.height=HEIGHT-20*HEIGHT/300;
			_gtxt.y=20*HEIGHT/300;
			_gtxt.text="SPEED\r0.0 KMPH";
			addChild(_gtxt);
			addEventListener(Event.ENTER_FRAME,_onEnterFrame);
			
			setSpeed(0);
		}
		
		private static var _textFormat:TextFormat;
		{
			_textFormat=new TextFormat();
			_textFormat.font=Fonts.DSDigitalBold;
			_textFormat.size=45*HEIGHT/300;
			_textFormat.align=TextFormatAlign.CENTER;
			_textFormat.color=Colours.FG;
		}
		
		private var _tileGFX:SpeedometerGFX;
		private var _gtxt:TextField;
		private var _pointer:DisplayObject;
		
		private var _gpsSensor:GPSModule;
		
		private var _speed:Number=0;
		private var _a:Number=0;
		
		private var _speedData:Vector.<Number>=new Vector.<Number>();
		
		public function setSpeed(speed:Number):void{
			_gtxt.text="SPEED\r"+speed.toFixed(1)+" KMPH";
			_speed=(speed>60)?60:speed;
			_speedData.push(speed);
		}
		
		private function _onEnterFrame(event:Event):void{
			var m:Matrix=new Matrix();
			_a+=0.1*(_speed*Math.PI/60-_a)
			m.rotate(_a);
			m.translate(100,180);
			_pointer.transform.matrix=m;
		}
		
		private function _onSensorData(event:SensorEvent):void{
			setSpeed(_gpsSensor.data[_gpsSensor.data.length-1].speed(NMEASentence.KILOMETRES_PER_HOUR));
		}
	}
}